package com.ctsi.ssdc.service.impl;


import com.ctsi.ssdc.domain.LitemallCouponExample;
import com.ctsi.ssdc.domain.LitemallCouponUser;
import com.ctsi.ssdc.domain.LitemallCouponUserExample;
import com.ctsi.ssdc.repository.LitemallCouponUserRepository;
import com.ctsi.ssdc.util.CouponConstant;
import org.springframework.stereotype.Service;
import org.apache.commons.collections.CollectionUtils;
import com.ctsi.ssdc.domain.LitemallCoupon;
import com.ctsi.ssdc.service.LitemallCouponService;
import com.ctsi.ssdc.repository.LitemallCouponRepository;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import com.ctsi.ssdc.model.PageResult;
import org.springframework.data.domain.Pageable;
import com.github.pagehelper.PageHelper;
/**
 * Service Implementation for managing LitemallCoupon.
 *
 * @author ctsi-biyi-generator
 *
 */
@Service
public class LitemallCouponServiceImpl 
	extends StrengthenBaseServiceImpl<LitemallCouponRepository, LitemallCoupon, Integer, LitemallCouponExample> 
	implements LitemallCouponService {

    @Autowired
    LitemallCouponRepository litemallCouponRepository;
    @Autowired
    LitemallCouponUserRepository litemallCouponUserRepository;

    private LitemallCoupon.Column[] result = new LitemallCoupon.Column[]{LitemallCoupon.Column.id, LitemallCoupon.Column.name, LitemallCoupon.Column.desc, LitemallCoupon.Column.tag,
            LitemallCoupon.Column.days, LitemallCoupon.Column.startTime, LitemallCoupon.Column.endTime,
            LitemallCoupon.Column.discount, LitemallCoupon.Column.min};


    /**
    * GET  /litemallCoupons : get the litemallCoupons firstStringBaseColumn.
    */
    @Override
    public PageResult<LitemallCoupon> findFirstStringColumn(String name,Pageable pageable){
        String str = name;
        if (Objects.nonNull(pageable)) {
            PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        }
        LitemallCouponExample litemallCouponExample = new LitemallCouponExample();
        String orderBy = getPageOrderBy(pageable);
        if(StringUtils.isNotEmpty(orderBy)) {
            litemallCouponExample.setOrderByClause(orderBy);
        }
        if (StringUtils.isEmpty(str)){
            litemallCouponExample.createCriteria();
        } else{
            litemallCouponExample.createCriteria().andNameLike("%" + str +"%");
        }
        List<LitemallCoupon>  data = litemallCouponRepository.selectByExample(litemallCouponExample);

        long count = 0L;
        if (CollectionUtils.isNotEmpty(data)){
            count = litemallCouponRepository.countByExample(litemallCouponExample);
        }
        return new PageResult<LitemallCoupon>(data,count,count);
    }

    @Override
    public List<LitemallCoupon> queryRegister() {
        LitemallCouponExample example = new LitemallCouponExample();
        example.or().andTypeEqualTo(CouponConstant.TYPE_REGISTER).andStatusEqualTo(CouponConstant.STATUS_NORMAL).andDeletedEqualTo(false);
        return litemallCouponRepository.selectByExample(example);
    }

    @Override
    public LitemallCoupon findById(Integer couponId) {
        return litemallCouponRepository.selectByPrimaryKey(couponId);
    }

    @Override
    public List<LitemallCoupon> queryList(int offset, int limit) {
        return queryList(offset, limit, "add_time", "desc");
    }
//
    @Override
    public List<LitemallCoupon> queryList(LitemallCouponExample.Criteria criteria, int offset, int limit, String sort, String order) {
        criteria.andTypeEqualTo(CouponConstant.TYPE_COMMON).andStatusEqualTo(CouponConstant.STATUS_NORMAL).andDeletedEqualTo(false);
        criteria.example().setOrderByClause(sort + " " + order);
        PageHelper.startPage(offset, limit);
        return litemallCouponRepository.selectByExampleSelective(criteria.example(), result);
    }

    @Override
    public List<LitemallCoupon> queryAvailableList(Integer userId, int offset, int limit) {
        assert userId != null;
        // 过滤掉登录账号已经领取过的coupon
        LitemallCouponExample.Criteria c = LitemallCouponExample.newAndCreateCriteria();
        List<LitemallCouponUser> used = litemallCouponUserRepository.selectByExample(
                LitemallCouponUserExample.newAndCreateCriteria().andUserIdEqualTo(userId).example()
        );
        if(used!=null && !used.isEmpty()){
            c.andIdNotIn(used.stream().map(LitemallCouponUser::getCouponId).collect(Collectors.toList()));
        }
        return queryList(c, offset, limit, "add_time", "desc");
    }

    @Override
    public LitemallCoupon findByCode(String code) {
        LitemallCouponExample example = new LitemallCouponExample();
        example.or().andCodeEqualTo(code).andTypeEqualTo(CouponConstant.TYPE_CODE).andStatusEqualTo(CouponConstant.STATUS_NORMAL).andDeletedEqualTo(false);
        List<LitemallCoupon> couponList =  litemallCouponRepository.selectByExample(example);
        if(couponList.size() > 1){
            throw new RuntimeException("");
        }
        else if(couponList.size() == 0){
            return null;
        }
        else {
            return couponList.get(0);
        }
    }

    public List<LitemallCoupon> queryList(int offset, int limit, String sort, String order) {
        return queryList(LitemallCouponExample.newAndCreateCriteria(), offset, limit, sort, order);
    }

    private String getPageOrderBy(Pageable page) {
        if(page!= null && page.getSort() != null) {
            StringBuilder sb = new StringBuilder();
            page.getSort().forEach(sort -> sb.append(sort.getProperty())
            .append(" ").append(sort.getDirection()).append(","));
            if(sb.length() > 1) {
                return (sb.substring(0,sb.length()-1));
             }
        }
        return null;
    }
}
